package cc.htdf.gwc.radar.service.impl;

import cc.htdf.gwc.radar.config.constants.Constants;
import cc.htdf.gwc.radar.domain.RadarGridMinutesData;
import cc.htdf.gwc.radar.repository.ForecastRepository;
import cc.htdf.gwc.radar.service.ForecastService;
import cc.htdf.gwc.radar.utils.RadarNcFileUtils;
import com.google.common.collect.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ucar.nc2.NetcdfFile;
import whisper.common.utils.DateUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by JT on 2017/11/13.
 */
@Service
public class ForecastServiceImpl implements ForecastService {

    @Autowired
    private ForecastRepository forecastRepository;

    @Override
    public void fileParsing(String fullpath) {
        /* 读取数据 */
        NetcdfFile file = RadarNcFileUtils.openNc(fullpath);
        long genTimestamp = readGentime(file);
        float[][][] rateData = readRateValue(file);
        RadarNcFileUtils.closeNc(file);

        /**
         * 数据筛选
         */
        Table<String, String[], int[]> gridInfoTable = Constants.GRID_INFO_TABLE;
        List<RadarGridMinutesData> gridMinutesDataList = new ArrayList<>();
        Map<String[], int[]> rowMap;
        RadarGridMinutesData gridMinutesData;
        String pattern = "yyyy-MM-dd HH:mm:ss", gentime = DateUtils.timestampToStr(genTimestamp * 1000, pattern);
        for (int i = 0; i < rateData.length; i++) {
            long validTimestamp = genTimestamp + i * 10 * 60;
            String validTime = DateUtils.timestampToStr(validTimestamp * 1000, pattern);

            for (String row : gridInfoTable.rowKeySet()) {
                rowMap = gridInfoTable.row(row);
                for (Map.Entry<String[], int[]> entry : rowMap.entrySet()) {
                    gridMinutesData = new RadarGridMinutesData();
                    gridMinutesData.setStationId(row);
                    gridMinutesData.setLat(entry.getKey()[0]);
                    gridMinutesData.setLon(entry.getKey()[1]);
                    gridMinutesData.setGentime(gentime);
                    gridMinutesData.setValidtime(validTime);
                    gridMinutesData.setQop10Minutes(String.format("%.2f", rateData[i][entry.getValue()[0]][entry.getValue()[1]]));
                    gridMinutesDataList.add(gridMinutesData);
                }
            }
        }

        forecastRepository.batchSaveGridMinutesData(gridMinutesDataList);

    }


    /**
     * 读取发布时间
     * @param nc
     * @return
     * @throws Exception
     */
    private long readGentime(NetcdfFile nc) {
        return RadarNcFileUtils.readVariableLong(nc, "gen_time");
    }

    /**
     *
     * 读取数据
     * @param nc
     * @return
     * @throws Exception
     */
    private float[][][] readRateValue(NetcdfFile nc) {
        return RadarNcFileUtils.readDatasThreeDimension(nc, "rate");
    }

}
